import struct
import sys
from optparse import OptionParser


parser = OptionParser()
parser.add_option("-i", "--input", dest="inputfile",
                  help="read binary code from FILE", metavar="FILE")
parser.add_option("-o", "--output", dest="outputfile",
                  help="write ADF output to FILE", metavar="FILE")
(options, args) = parser.parse_args()

if options.inputfile==None or options.outputfile==None:
  print "Input and output files must be specified"
  sys.exit(1)


#Read our bootblock data...
print "Reading "+options.inputfile
f=open(options.inputfile,'rb')
bootblock=f.read()
f.close()

#Make sure it will fit...
if len(bootblock)>1024:
  print("The bootblock is too large")
  sys.exit(1)

#Pad the loaded bootblock data out to the correct length, i.e. 1024 bytes,
#which is 2 sectors...
while(len(bootblock)<1024):
  bootblock+="\0"

#Calculate checksum of bootblock
checksum=0
for i in range(1024/4):
  thislong=ord(bootblock[i*4])<<24
  thislong+=ord(bootblock[i*4+1])<<16
  thislong+=ord(bootblock[i*4+2])<<8
  thislong+=ord(bootblock[i*4+3])
  checksum+=thislong
  if checksum>0xFFFFFFFF:
    checksum-=0x100000000
    checksum+=1
checksum^=0xFFFFFFFF
bootblock=bootblock[:4]+struct.pack('>L',checksum)+bootblock[8:]

#Write the ADF file, which is basically the entire disk's worth of data
#arranged sector by track for a total length of 901120 bytes...
of=open(options.outputfile,'wb')
of.write(bootblock)

#Pad any unused disk space with 0's...
restofdisk=901120-len(bootblock)
for i in range(restofdisk):
  of.write('\0')
of.close()
print "Generated "+options.outputfile

